const express  = require ('express');
const pool = require('../pool');
const session = require('express-session');
const router = express.Router();


function query(sql, data = {}, isCount = false) {
    return new Promise((resolve, reject) => {
        Object.values(data).forEach(item => {
            sql = sql.replace("?", item)
        })
        if (Array.isArray(sql)) {
            Promise.all((sql.map(item => {
                return new Promise((res, rej) => {
                    pool.query(item, function (qerr, vals, fields) {
                        res(vals)
                    })
                })
            }))).then(res => {
                resolve(res)
            })
        } else {
            pool.query(sql, function (qerr, vals, fields) {
                //事件驱动回调
                if (qerr) {
                    console.log(qerr)
                    reject(new Error('sql语句执行发生错误'))
                } else {
                    if (isCount) {
                        pool.query(`SELECT FOUND_ROWS() as count`, function (error, count) {
                            resolve({
                                data: vals,
                                count: count[0].count
                            })
                        })
                    } else {
                        resolve(vals)
                    }
                }
            });
        }

    })
}

router.get('/queryAll',(req,res,next)=>{
    let page = (req.query.page - 1) * 18;
    let pageCount = 18
    pool.query(`select id,name,imgUrl,price from commodity  limit ${page},${pageCount}`,(err,r)=>{
        if(err){
            return next(err)
        }
        pool.query('select count(*) from commodity',(err,resp)=>{
            if(err){
                return next(err)
            }
            let pageSize = Math.ceil(resp[0]['count(*)']/18)
            if(r.length !=0){
                res.send({code:200,data:{result:r,pageSize}})
            }else{
                res.send({code:400,data:'没有更多'})
            }
        })
    })
})

router.get('/queryById',(req,res,next)=>{
    let id = req.query.id;
    pool.query(`select * from commodity where id=${id}`,(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,data:r[0]})
    })
})

router.post('/cart_list',async(req,res,next)=>{
    let { goodsList } = req.body;
    for(let i=0;i<goodsList.length;i++){
        const goods = goodsList[i];
        let [info] = await getGoodsLsit(goods.id)
        info.select = false;
        info.total = 0;
        //info.urlList = JSON.parse(info.urlList)
        goodsList[i] = Object.assign(info, goods)
    }
    res.send({code:200,data:goodsList})
})

router.get('/shoppinfo',(req,res,next)=>{
    let id = req.query.id;
    commoditybyid(id,function (err,data){
        if(err){
            return next(err)
        }
        res.send({code:200,data:data})
    })
})

router.post('/addshopcardinfo',(req,res,next)=>{
    addshopcardinfo({
        username: req.body.user.nickname,
        u_id: req.body.user.u_id,
        comm: req.body.data,
        date: new Date(),
        total: req.body.total,
        orderState: 0
    },async function(err,data){
        if(err){
            return next(err)
        }
        let prList = JSON.parse(req.body.data).map(async (v)=>{
            await changeStoke(v.id,{
                number:-Number(v.number)
            })
        })
        await Promise.all(prList)
        return res.send({code:200,data:'添加商品成功'})
    })
})

router.post('/addComm',(req,res,next)=>{
    let bodys = req.body;
    addComm({
        commText:bodys.commText,
        goodsId:bodys.goodsId,
        userId:bodys.uid,
        date:new Date()
    },function(err,data){
        if(err){
            return next(err)
        }
        if(data){
            res.send({code:200,msg:'发表成功'})
        }else{
            res.send({code:200,msg:'发表失败'})
        }
    })
})

router.get('/AllComm',(req,res,next)=>{
    let id = req.query.id;
    pool.query(`select userId,commDate,commText from comm where goodsId=${id}`,(err,r)=>{
        if(err){
            return next(err)
        }
        if(r.length>0){
            res.send({code:200,data:r})
        }else{
            res.send({code:400,data:'暂无评论'})
        }
    })
})

function getGoodsLsit(id){
    return new Promise((resolve,reject)=>{
        query('select * from commodity where id=?',{id})
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}

function commoditybyid(id,callback){
    pool.query(`select * from commodity where id=${id}`,(err,r)=>{
        if(err){
            callback(err)
        }else{
            callback(null,r)
        }
    })
}

function addshopcardinfo(data,callback){
    console.log(data)
    pool.query(`insert into card values(null,?,?,?,?,?,${data.total})`,[data.u_id,data.username,data.date,data.orderState,data.comm],(err,r)=>{
        if(err){
            callback(err)
        }else{
            callback(null,r)
        }
    })
}

function changeStoke(id,data){
    return new Promise((resolve,reject)=>{
        let sql =  `stoke=stoke+${data.number}`;
        query(`update commodity set ${sql} where id=${id}`)
            .then(res=>{
                resolve(res)
            })
            .catch(err=>{
                reject(reject)
            })
    })
}

function addComm(data,callback){
    let obj = sqlAddStr(data);
    pool.query(`insert into comm values(null,${data.userId},${data.goodsId},?,?)`,[data.commText,data.date],(err,r)=>{
        if(err){
            callback(err)
        }else{
            callback(null,r)
        }
    })
}

function sqlAddStr(data){
    let vals = [];
    let keys = Object.keys(data);
    Object.entries(data).forEach(item=>{
        if(keys.includes(item[0])){
            vals.push(JSON.stringify(item[1]))
        }
    })

    return{
        keys:keys.join(','),
        vals:keys.join(',')
    }
}

module.exports = router;